package com.tyl.unsafa;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

public class SetTest {
    // java.util.ConcurrentModificationException 并发修改异常
    public static void main(String[] args) {

        // Set<String> set = new HashSet<>();在并发中用ArrayList不安全
        /**
         *解决方法
         * 1、Set<String> set = Collections.synchronizedSet(new HashSet<>());工具类写法
         * 2、 Set<String> set =new CopyOnWriteArraySet<>();利用CopyOnWrite增加效率
         * **/
        Set<String> set =new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,5));
                System.out.println(set);
            },String.valueOf(i)).start();
        }
    }
}
